package com.wimcorp.magic.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.wimcorp.magic.userinterface.GameInterface;

public class Client {

	public static void main(String[] args) {
		try {
			GameInterface game = createGame();
			String playerName = getPlayerInput("Enter player name : ");
			CommandLineInterface playerInterface = new CommandLineInterface(playerName, game);
			game.register(playerName, playerInterface);
			playerInterface.selectDeck();
			playerInterface.confirmReady();
			playerInterface.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static GameInterface createGame() throws IOException, RemoteException, AccessException {
		Registry registry = LocateRegistry.getRegistry("localhost", 6123);
		GameInterface game = null;
		while (game == null) {
			String gameName = getPlayerInput("Enter game name : ");
			try {
				game = (GameInterface) registry.lookup(gameName);
			} catch (NotBoundException e) {
				System.out.println("Game with name : " + gameName + " not found. ");
				game = null;
			}
		}
		return game;
	}

	private static String getPlayerInput(String message) throws IOException, RemoteException {
		BufferedReader bufferRead;
		String input = "";
		while (input.length() == 0) {
			System.out.println(message);
			bufferRead = new BufferedReader(new InputStreamReader(System.in));
			input = bufferRead.readLine();
			if (input.length() == 0) {
				System.out.println("Input should not be at least 1 character. ");
			}
		}
		return input;
	}
}
